import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import config from '../api/config'

// create an axios instance
const service = axios.create({
  baseURL: config.webServiceUrl, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    console.log(config)
    if (store.getters.token) {
      config.headers['satoken'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.success === false) {
      Message({
        message: response.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // 如果时请求文件的接口在这里做处理，判断路由名称返回hander参数！！
      return response
    }
  },
  error => {
    console.log('err' + error)
    if (error.response.status === 401) { // token过期处理
      Message({
        message: '身份信息已过期,请重新登陆',
        type: 'warning',
        duration: 3 * 1000
      })
      router.push({ path: '/login' })
    }
    return Promise.reject(error)
  }
)

export default service
